<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>查询商品</title>
    <!-- 引入 ajax 工具 -->
    <script src="/wbs20052/ajax/day01/ajaxUtil.js" ></script>
    <script>
        function getProduct2() {
            var pid = document.getElementById("pid").value;
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function(){
                // 当 readyState 是 4，并且 status 是 200 的时候，才能够正常的处理服务器响应的数据。
                if(xhr.readyState == 4 && xhr.status == 200){
                    // console.log('readyState:', xhr.readyState);
                    // console.log("responseText:", xhr.responseText);
                    var obj = JSON.parse(xhr.responseText);
                    document.getElementById("name").innerText = obj.p_name;
                    document.getElementById("price").innerText = obj.p_price;
                }
            };

            xhr.open("post", "http://localhost/wbs20052/ajax/day01/getProduct.php", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            // xhr.responseType = "json";
            xhr.send("pid=" + pid);

            // 目前只能延时获取响应数据
            // setTimeout(function(){
            //     // console.log("responseText:", xhr.responseText);// 设置为 json 时，不能使用
            //     console.log("response:", xhr.response);
            // }, 3000);
            
        }
        function getProduct() {
            var pid = document.getElementById("pid").value;
            var option = {
                method: "post",
                url: "http://localhost/wbs20052/ajax/day01/getProduct.php",
                data: "pid=" + pid,
                success: function(xhr){
                    if(xhr.status == 200){
                        console.log(xhr.responseText);

                        var obj = JSON.parse(xhr.responseText);
                        document.getElementById("name").innerText = obj.p_name;
                        document.getElementById("price").innerText = obj.p_price;
                    } else {
                        console.log("status=", xhr.status);
                    }
                }
            };
            ajax(option);
        }
    </script>
</head>
<body>
    <input type="text" id="pid" placeholder="请输入商品编号">
    <input type="button" value="查询" onclick="getProduct()" >
    <div>
        <h3>商品信息</h3>
        <div>
            <div id="name"></div>
            <div id="price"></div>
        </div>
    </div>
</body>
</html>